package com.gongpingjialoan.activity.sell;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.CarBuyDetailActivity;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.BaseScrollFragment;
import com.gongpingjialoan.adapter.PhotoGridAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.PhotoModel;
import com.gongpingjialoan.bean.PriCarPhotoItem;
import com.gongpingjialoan.bean.SellPrivateDetail;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.widget.AddMaintainView;
import com.gongpingjialoan.widget.ModPriceDialog;
import com.gongpingjialoan.widget.MyGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/10/11.
 */
public class OnSellPrivateCarDetailFragment extends BaseScrollFragment implements View.OnClickListener {

    private View view;

    private NetDataJson modifyNetDataJson;

    private BaseActivity mActivity;

    private View car_detail;


    private TextView carNameTextView, timeTextView, mileTextView, statusTextView, browseTextView, collectTextView,
            priceTextView, nameTextView, phoneTextView, addressTextView, destTextView, mod_priceTextView;

    private SellPrivateDetail.DataEntity dataEntity;

    private MyGridView carPhotoMyGridView, indMyGridView;

    private AddMaintainView baoyangView, chuxiangView, otherAddMaintainView;

    private PhotoGridAdapter mCarPhotoGridAdapter, indPhotoGridAdapter;

    private List<PriCarPhotoItem> mPriCarPhotoItems, indePriCarPhotoItems;

    private ModPriceDialog mModPriceDialog;

    private String newPrice = "";


    public OnSellPrivateCarDetailFragment(SellPrivateDetail.DataEntity dataEntity) {
        this.dataEntity = dataEntity;
    }



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.on_sellprivate_layout, container, false);
        initView();
        initData();
        return view;
    }

    private void initView() {
        mActivity = (BaseActivity) getActivity();
        car_detail = view.findViewById(R.id.car_detail);

        browseTextView = (TextView) view.findViewById(R.id.browse);
        collectTextView = (TextView) view.findViewById(R.id.collect);
        mod_priceTextView = (TextView) view.findViewById(R.id.mod_price);
        mod_priceTextView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        mod_priceTextView.getPaint().setAntiAlias(true);//抗锯齿
        mod_priceTextView.setOnClickListener(this);
        destTextView = (TextView) view.findViewById(R.id.desc_txt);
        carNameTextView = (TextView) view.findViewById(R.id.carName);
        timeTextView = (TextView) view.findViewById(R.id.time);
        mileTextView = (TextView) view.findViewById(R.id.mile);
        statusTextView = (TextView) view.findViewById(R.id.status);
        priceTextView = (TextView) view.findViewById(R.id.price);
        nameTextView = (TextView) view.findViewById(R.id.name);
        phoneTextView = (TextView) view.findViewById(R.id.phone);
        addressTextView = (TextView) view.findViewById(R.id.address);
        carPhotoMyGridView = (MyGridView) view.findViewById(R.id.car_photos);
        indMyGridView = (MyGridView) view.findViewById(R.id.ind_photos);
        baoyangView = (AddMaintainView) view.findViewById(R.id.maintain);
        chuxiangView = (AddMaintainView) view.findViewById(R.id.chuxian);
        otherAddMaintainView = (AddMaintainView) view.findViewById(R.id.other);
        baoyangView.setTitle("最近保养记录");
        chuxiangView.setTitle("最近出险记录");
        otherAddMaintainView.setTitle("其它图片");
        baoyangView.isEdit = false;
        chuxiangView.isEdit = false;
        baoyangView.setImgVis();
        chuxiangView.setImgVis();
        otherAddMaintainView.isEdit = false;
        otherAddMaintainView.setImgVis();

        mPriCarPhotoItems = new ArrayList<>();
        indePriCarPhotoItems = new ArrayList<>();
        mCarPhotoGridAdapter = new PhotoGridAdapter(mPriCarPhotoItems, mActivity, false);
        indPhotoGridAdapter = new PhotoGridAdapter(indePriCarPhotoItems, mActivity, false);
        carPhotoMyGridView.setAdapter(mCarPhotoGridAdapter);
        indMyGridView.setAdapter(indPhotoGridAdapter);

        car_detail.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if (v == mod_priceTextView) {
            mModPriceDialog = new ModPriceDialog(mActivity, dataEntity.getEval_price());
            mModPriceDialog.show();
        } else if (v == car_detail) {
            Intent intent = new Intent();
            intent.setClass(mActivity, CarBuyDetailActivity.class);
            if (dataEntity == null) return;
            intent.putExtra("typevalue", dataEntity.getCar_source_id());
            intent.putExtra("city", dataEntity.getCity());
            startActivity(intent);
        }
    }


    private void initData() {

        carNameTextView.setText(dataEntity.getTitle());
        if (dataEntity.getCreate_time().length() > 10) {
            timeTextView.setText(dataEntity.getCreate_time().substring(0, 10));
        }

        String status = "信息状态: " + dataEntity.getStatus_zh();
        statusTextView.setText(Utils.changeColor(mActivity, status, 0, 6, R.color.discount_price_other_color));
        mileTextView.setText(dataEntity.getYear() + "年上牌/" + dataEntity.getMile() + "万公里");
        priceTextView.setText(dataEntity.getPrice() + "万");
        nameTextView.setText(dataEntity.getContact());
        phoneTextView.setText(dataEntity.getPhone());
        addressTextView.setText(dataEntity.getRegion());
        browseTextView.setText("浏览数: " + dataEntity.getCar_source_info().getView_times());
        collectTextView.setText("收藏数: " + dataEntity.getCar_source_info().getLike_times());
        if (!TextUtils.isEmpty(dataEntity.getDescription())) {
            destTextView.setText(dataEntity.getDescription());
        }

        List<SellPrivateDetail.DataEntity.ImagesEntity> imagesEntities = dataEntity.getImages();
        if (imagesEntities != null && imagesEntities.size() > 0) {
            int size = imagesEntities.size();
            int length = Const.CarTypes.length;
            for (int i = 0; i < size; i++) {
                String type = imagesEntities.get(i).getName();
                for (int j = 0; j < length; j++) {
                    if (type.equals(Const.CarTypes[j])) {
                        PriCarPhotoItem item = new PriCarPhotoItem(imagesEntities.get(i).getUrl(), Const.CarTypes[j], Const.CarNames[j]);
                        mPriCarPhotoItems.add(item);
                    }
                }
            }
            mCarPhotoGridAdapter.notifyDataSetChanged();
        }

        List<SellPrivateDetail.DataEntity.ImagesEntity> indImagesEntityList = dataEntity.getIdentify_images();
        if (indImagesEntityList != null && indImagesEntityList.size() > 0) {
            int size = indImagesEntityList.size();
            int length = Const.IndTypes.length;
            for (int i = 0; i < size; i++) {
                String type = indImagesEntityList.get(i).getName();
                for (int j = 0; j < length; j++) {
                    if (type.equals(Const.IndTypes[j])) {
                        PriCarPhotoItem item = new PriCarPhotoItem(indImagesEntityList.get(i).getUrl(), Const.IndTypes[j], Const.IndNames[j]);
                        indePriCarPhotoItems.add(item);
                    }
                }
            }
            indPhotoGridAdapter.notifyDataSetChanged();
        }

        List<SellPrivateDetail.DataEntity.ImagesEntity> maintenanceImages = dataEntity.getMaintenance_images();
        if (maintenanceImages != null && maintenanceImages.size() > 0) {
            List<PhotoModel> images = new ArrayList<>();
            int size = maintenanceImages.size();
            for (int i = 0; i < size; i++) {
                PhotoModel photoModel = new PhotoModel();
                photoModel.setUploadedUrl(maintenanceImages.get(i).getUrl());
                photoModel.setIsLoading(true);
                photoModel.setId(0);
                images.add(photoModel);
            }
            baoyangView.setData(images);
        } else {
            baoyangView.setVisibility(View.GONE);
        }

        List<SellPrivateDetail.DataEntity.ImagesEntity> insureImagesEntityList = dataEntity.getInsurance_images();
        if (insureImagesEntityList != null && insureImagesEntityList.size() > 0) {
            List<PhotoModel> images = new ArrayList<>();
            int size = insureImagesEntityList.size();
            for (int i = 0; i < size; i++) {
                PhotoModel photoModel = new PhotoModel();
                photoModel.setUploadedUrl(insureImagesEntityList.get(i).getUrl());
                photoModel.setIsLoading(true);
                photoModel.setId(0);
                images.add(photoModel);
            }
            chuxiangView.setData(images);
        } else {
            chuxiangView.setVisibility(View.GONE);
        }


        List<SellPrivateDetail.DataEntity.ImagesEntity> otherImagesEntities = dataEntity.getOther_images();
        if (otherImagesEntities != null && otherImagesEntities.size() > 0) {
            List<PhotoModel> images = new ArrayList<>();
            int size = otherImagesEntities.size();
            for (int i = 0; i < size; i++) {
                PhotoModel photoModel = new PhotoModel();
                photoModel.setUploadedUrl(otherImagesEntities.get(i).getUrl());
                photoModel.setIsLoading(true);
                photoModel.setId(0);
                images.add(photoModel);
            }
            otherAddMaintainView.setData(images);
        } else {
            otherAddMaintainView.setVisibility(View.GONE);
            view.findViewById(R.id.other_l).setVisibility(View.GONE);
        }

        if ((maintenanceImages.size() + insureImagesEntityList.size()) == 0) {
            view.findViewById(R.id.tese).setVisibility(View.GONE);
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        if (modifyNetDataJson != null) {
            modifyNetDataJson.cancelTask();
            modifyNetDataJson = null;
        }

    }


    public void modifyPrice(String price) {
        newPrice = price;
        try {
            if (modifyNetDataJson == null) {
                modifyNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                    @Override
                    public void onDataJsonError(String errorMessage) {
                        mActivity.hidenProgressDialog();
                        Toast.makeText(mActivity, errorMessage, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onDataJsonUpdate(JSONObject json) {
                        mActivity.hidenProgressDialog();
                        priceTextView.setText(newPrice + "万");
                        Toast.makeText(mActivity, "修改成功!", Toast.LENGTH_SHORT).show();
                    }
                });
            }
            modifyNetDataJson.setUrl(API.modify_private_car);
            modifyNetDataJson.addParam("brand", dataEntity.getBrand());
            modifyNetDataJson.addParam("model", dataEntity.getModel());
            modifyNetDataJson.addParam("model_detail", dataEntity.getModel_detail());
            modifyNetDataJson.addParam("year", dataEntity.getYear());
            modifyNetDataJson.addParam("month", dataEntity.getMonth());
            modifyNetDataJson.addParam("mile", dataEntity.getMile());
            modifyNetDataJson.addParam("city", dataEntity.getCity());
            modifyNetDataJson.addParam("price", price);
            modifyNetDataJson.addParam("region", dataEntity.getRegion());
            modifyNetDataJson.addParam("contact", dataEntity.getContact());
            modifyNetDataJson.addParam("phone", dataEntity.getPhone());
            modifyNetDataJson.addParam("id", dataEntity.getId());
            modifyNetDataJson.addParam("description", dataEntity.getDescription());
            modifyNetDataJson.addParam("images", getGridViewImages(mCarPhotoGridAdapter, Const.CarTypes).toString());
            modifyNetDataJson.addParam("identify_images", getGridViewImages(indPhotoGridAdapter, Const.IndTypes).toString());
            modifyNetDataJson.addParam("maintenance_images", baoyangView.getUrls().toString());
            modifyNetDataJson.addParam("insurance_images", chuxiangView.getUrls().toString());
            modifyNetDataJson.request("post");
            mActivity.showProgressDialog("加载中...");
        } catch (JSONException e) {

        }
    }


    public JSONArray getGridViewImages(PhotoGridAdapter adapter, String[] types) throws JSONException {
        JSONArray jsa = new JSONArray();
        int size = adapter.getCount();
        for (int i = 0; i < size; i++) {
            PriCarPhotoItem item = (PriCarPhotoItem) adapter.getItem(i);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", types[i]);
            jsonObject.put("url", item.getImgUrl());
            jsa.put(jsonObject);
        }
        return jsa;
    }
}
